<script lang="ts" setup>
import type { RoleModel } from '#/api/system/models';

import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';

import { Button, Popconfirm, Space, Tag } from 'ant-design-vue';

import { useVbenVxeGrid, type VxeGridProps } from '#/adapter/vxe-table';
import { deleteRoleApi, getRolePagedListApi } from '#/api/system/role';

import RoleFormModal from './form-modal.vue';
import RoleMenuFormDrawer from './role-menu-drawer.vue';

defineOptions({ name: 'SystemRole' });

const gridOptions: VxeGridProps<RoleModel> = {
  columns: [
    { type: 'seq', width: 70 },
    { field: 'name', title: '角色名称', width: 180 },
    { field: 'code', title: '角色编码', width: 180 },
    { field: 'order', title: '排序', width: 60 },
    { field: 'status', title: '状态', width: 90, slots: { default: 'status' } },
    { field: 'createdTime', title: '创建时间', width: 160 },
    { field: 'remark', title: '备注', minWidth: 100 },
    {
      field: 'action',
      title: '操作',
      fixed: 'right',
      width: 220,
      slots: { default: 'action' },
    },
  ],
  border: true,
  height: 'auto',
  stripe: true,
  rowConfig: {
    isHover: true,
  },
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        return await getRolePagedListApi({
          pageNumber: page.currentPage,
          pageSize: page.pageSize,
        });
      },
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: RoleFormModal,
});

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: RoleMenuFormDrawer,
});

function openFormModal(row?: RoleModel) {
  formModalApi.setData({ values: row });
  formModalApi.open();
}

function openFormDrawer(row?: RoleModel) {
  formDrawerApi.setData(row);
  formDrawerApi.open();
}

async function deleteHandle(row: RoleModel) {
  await deleteRoleApi(row.id);
  gridApi.reload();
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-tools>
        <Space>
          <Button type="primary" @click="openFormModal()"> 新增角色 </Button>
        </Space>
      </template>
      <template #status="{ row }">
        <Tag :color="row.status === 1 ? 'green' : 'red'">
          {{ row.status === 1 ? '启用' : '停用' }}
        </Tag>
      </template>
      <template #action="{ row }">
        <Button size="small" type="link" @click="openFormDrawer(row)">
          授权菜单
        </Button>
        <Button size="small" type="link" @click="openFormModal(row)">
          编辑
        </Button>
        <Popconfirm title="确定要删除吗？" @confirm="deleteHandle(row)">
          <Button size="small" type="link"> 删除 </Button>
        </Popconfirm>
      </template>
    </Grid>
    <FormModal @complete="() => gridApi.reload()" />
    <FormDrawer />
  </Page>
</template>
